<%@ include file="/WEB-INF/jsp/common/include.jsp" %><%@ page
    pageEncoding="UTF-8"%><%@ page
    import="java.util.List"%><%@ page
    import="java.util.ArrayList"%><%@ page
    import="com.google.appengine.api.datastore.Key"%><%@ page
    import="com.bac.rentmap.ad.flat.search.SearchParameters"%><%@ page
    import="com.bac.rentmap.ad.flat.FlatAd"%><%@ page
    import="com.google.appengine.api.users.UserService"%><%@ page
    import="com.google.appengine.api.users.UserServiceFactory"%><%@ page
    import="com.google.appengine.api.images.ServingUrlOptions"%><%@ page
    import="com.google.appengine.api.images.ImagesService"%><%@ page
    import="com.google.appengine.api.blobstore.BlobKey"%><%@ page
    import="com.bac.rentmap.map.thumbnail.Point"%>
<%@ page import="java.util.Map" %>
<%@ page import="com.bac.rentmap.ad.flat.image.FlatImageType" %>
<%@ taglib
    uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %><%@ taglib
    prefix="app" uri="AppTags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<tiles:insertDefinition name="searchLayout.tiles">
  <tiles:putAttribute name="pageMessageKey">search.list</tiles:putAttribute>
  <tiles:putAttribute name="adListTab" cascade="true">selected</tiles:putAttribute>
  <tiles:putAttribute name="searchResult" cascade="true">
    <script>
      var flatAds = {};
      $("#price-range").slider({
        range: true,
        min: minPrice - step,
        max: maxPrice + step,
        values: [curMinPrice, curMaxPrice],
        step: step,
        slide: function(event, ui) {
          var newMinPrice = ui.values[0];
          if(newMinPrice < minPrice){
            newMinPrice = '';
          }
          $("#minPrice").val(newMinPrice);
          var newMaxPrice = ui.values[1];
          if(newMaxPrice > maxPrice){
            newMaxPrice = '';
          }
          $("#maxPrice").val(newMaxPrice);
          updatePriceRangeLabel(ui.values[0], ui.values[1])
        }
      });
      $(function() {
        $(".scrollable").each(function() {
          $(this).elastislide();
        });
        $.superbox.settings = {
          loadTxt:'Загрузка...',
          closeTxt: 'Закрыть',
          prevTxt: 'Предыдущая',
          nextTxt: 'Следующая'
        };
        $.superbox();
        $(window).scroll(function(e){
          var newFlatAds = {};
          for(var flatAd in flatAds){
            var flatAdElement = document.getElementById('flatAd' + flatAd);
            if(isElementInViewport(flatAdElement)){
              $.post('<app:slaveServerUrl />/ad/user/view/statistics/inc.do?flatAdId=' + flatAd);
            }
            else{
              newFlatAds[flatAd] = true;
            }
          }
          flatAds = newFlatAds;
        });
      });
      function isElementInViewport (el) {
        var rect = el.getBoundingClientRect();
        return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
        );
      }
      if(readCookie('showUserReviewThankYou') == 'true'){
        alert('Спасибо за отзыв. Ваш отзыв будет рассмотрен в ближайшее время.');
      }
      eraseCookie('showUserReviewThankYou');
    </script>
    <script type="text/javascript" src="<app:slaveServerUrl />/js/jquery/plugins/superbox/jquery.superbox.js"></script>
    <div id="list">
      <%
        UserService userService = UserServiceFactory.getUserService();
        int currentPage = ((SearchParameters)request.getAttribute("searchParameters")).getPage();
        pageContext.setAttribute("currentPage", currentPage);
        ImagesService imagesService = (ImagesService)request.getAttribute("imagesService");
      %>
      <!--List item-->
      <c:forEach var="flatAd1" items="${flatAds}" varStatus="status">
        <c:set var="flatAd" value="${flatAd1}" scope="request"/>
        <c:if test="${not empty flatAd}">
          <c:set var="normalizedRating" value="${normalizedRatings[status.count - 1]}" scope="request"/>
          <c:if test="${status.count == 6}">
            <div class="box white-box" style="padding: 15px">
              <c:choose>
                <c:when test="${currentPage >= 0}">
                  <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
                  <!-- hatu-by-bottom-responsive -->
                  <ins class="adsbygoogle"
                       style="display:block"
                       data-ad-client="ca-pub-2127591047178376"
                       data-ad-slot="2708728641"
                       data-ad-format="auto"></ins>
                  <script>
                    (adsbygoogle = window.adsbygoogle || []).push({});
                  </script>
                </c:when>
                <c:otherwise>
                  <a href="http://bling.by/?partner=2"><img src="<app:slaveServerUrl />/image/external/bling.jpg" style="border-radius: 4px; margin-bottom: 10px" title="bling.by" alt="bling.by"/></a>
                </c:otherwise>
              </c:choose>
            </div>
          </c:if>
          <c:set var="thumbnailPoint" value="${thumbnailPoints[status.count - 1]}"/>
          <c:if test="${not empty flatAd.secureId}">
            <script>
              flatAds["<c:out value='${flatAd.id}'/>"] = true;
            </script>
          </c:if>
          <!--List item-->
          <tiles:insertDefinition name="adContent.tiles">
            <tiles:putAttribute name="images">
              <%
                FlatAd flatAd = (FlatAd)request.getAttribute("flatAd");
                List flatImages = new ArrayList();
                Map flatImageBlobs = flatAd.getFlatImageBlobs();
                if(flatImageBlobs != null && flatImageBlobs.isEmpty()){
                  flatImageBlobs = null;
                }
                if(flatAd.getExternal()){
                  flatImages = flatAd.getExternalImages();
                }
                else if(flatImageBlobs != null) {
                  for(FlatImageType flatImageType: FlatImageType.values()){
                    BlobKey blobKey = (BlobKey)flatImageBlobs.get(flatImageType);
                    if(blobKey != null){
                      flatImages.add(blobKey);
                    }
                  }
                }else{
                  for (Key flatImageKey : flatAd.getFlatImages()) {
                    flatImages.add(flatImageKey.getId());
                  }
                }
                pageContext.setAttribute("flatImages", flatImages);
                Point thumbnailPoint = (Point)pageContext.getAttribute("thumbnailPoint");
                boolean mapLocationDefined = thumbnailPoint != null;
                pageContext.setAttribute("mapLocationDefined", mapLocationDefined);
                int locationImageCount = mapLocationDefined ? 1 : 0;
                if(mapLocationDefined){
                  pageContext.setAttribute("locationImageX", thumbnailPoint.getX());
                  pageContext.setAttribute("locationImageY", thumbnailPoint.getY());
                }
                pageContext.setAttribute("flatImageBlobs", flatImageBlobs);
              %>
              <c:if test="${mapLocationDefined || not empty flatImages}">
                <%

                  final int imageCountPerSection = 4;
                  int imageCount = (flatImageBlobs == null ? flatImages.size() : flatImageBlobs.size()) + locationImageCount;
                  if(currentPage > 10 && imageCount > 2){
                    imageCount = 2; // restrict image count on less used pages
                  }
                  int sectionCount = imageCount / imageCountPerSection;;
                  if(imageCount % imageCountPerSection != 0){
                    sectionCount++;
                  }
                %>
                <a class='prev browse left <%= sectionCount > 1 ? "" : "disabled" %>'></a>
                <ul class="scrollable elastislide-list">
                  <%
                    for(int i = 0; i < imageCount; i++){
                      if(i < locationImageCount){
                  %>
                  <li><a href="#" data-href="#osm-${flatAd.city}-${flatAd.agent ? 'agent' : 'owner'}-${flatAd.lat}-${flatAd.lon}-${flatAd.street}"
                         rel="superbox[gallery][flatGallery${flatAd.id}]">
                    <img src="/image/city/${flatAd.city}-small.png" />
                    <img src="/image/map/${flatAd.agent ? 'agent' : 'owner'}-map.png" class="imageGalleryMarker" style="left : ${locationImageX - 10}px; top : ${140 - locationImageY - 12}px"/>
                  </a></li>
                  <%
                  }
                  else{
                    pageContext.setAttribute("flatImageId", flatImages.get(i - locationImageCount));
                    try{
                  %>
                  <li><a href="#"
                      <c:choose>
                        <c:when test="${flatImageBlobs != null}">data-href="<%=imagesService.getServingUrl(ServingUrlOptions.Builder.withBlobKey((BlobKey)flatImages.get(i - locationImageCount)))%>"</c:when>
                        <c:otherwise>data-href="${flatImageId}"</c:otherwise>
                      </c:choose>
                         rel="superbox[gallery][flatGallery${flatAd.id}]">
                    <c:choose>
                      <c:when test="${flatAd.external}">
                        <img src="${flatImageId}" />
                      </c:when>
                      <c:when test="${flatImageBlobs != null}">
                        <img src="<%=imagesService.getServingUrl(ServingUrlOptions.Builder.withBlobKey((BlobKey)flatImages.get(i - locationImageCount)))%>=s140-c" />
                      </c:when>
                      <c:otherwise>
                        <img src="/ad/image/serve/thumbnail.do?flatImageId=${flatImageId}" />
                      </c:otherwise>
                    </c:choose>
                  </a></li>
                  <%
                        }catch(com.google.appengine.api.images.ImagesServiceFailureException exception){
                        }
                      }
                    }
                  %>
                </ul>
                <a class='next browse right <%= sectionCount > 1 ? "" : "disabled" %>'></a>
                <div style="clear:both"></div>
              </c:if>
            </tiles:putAttribute>
          </tiles:insertDefinition>
        </c:if>
      </c:forEach>
    </div>
    <!--Paging-->
    <div class="paging white-box" style="min-height: 52px">
      <ul>
        <tiles:insertTemplate template="prevButton.jsp"/>
        <tiles:insertTemplate template="nextButton.jsp"/>
      </ul>
      <ul class="num">
        <%
          int startIndex = Math.max(0, currentPage - 9);
          for(int i = startIndex; i < currentPage; i++){
        %>
        <c:url value="/ad/search/list.do" var="pageLink">
          <c:param name="minPrice" value="${searchParameters.minPrice}"/>
          <c:param name="maxPrice" value="${searchParameters.maxPrice}"/>
          <c:param name="room" value="${searchParameters.room}"/>
          <c:param name="page"><%= i %></c:param>
          <c:if test="${loggedIn}">
            <c:param name="loggedIn" value="${loggedIn}"/>
          </c:if>
        </c:url>
        <li><a href="${pageLink}"><%= i + 1 %></a></li>
        <%
          }
        %>
        <c:if test="${searchParameters.page gt 0}">
          <li><b>${searchParameters.page + 1}</b></li>
        </c:if>
      </ul>
    </div>
    <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
  </tiles:putAttribute>
</tiles:insertDefinition>